﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Web;

namespace WCF_projecto
{
    public class TokenAuth : ServiceAuthorizationManager
    {
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            string password = "123";
            // byte array representation of that string
            byte[] encodedPassword = new UTF8Encoding().GetBytes(password);
            // need MD5 to calculate the hash
            byte[] hash = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);
            // string representation (similar to UNIX format)
            string encoded = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
            var requestMessage = operationContext.RequestContext.RequestMessage;
            var opName = requestMessage.Properties["HttpOperationName"];

            var requestProperty = (HttpRequestMessageProperty)requestMessage.Properties[HttpRequestMessageProperty.Name];
            var token = requestProperty.Headers["Authorization"];
            if (!string.IsNullOrEmpty(token) && token.Equals(encoded))
            {
                return true;
            }
            return false;
        }
    }
}